package com.wangxl.rabbitmqdemo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
@Slf4j
public class ObjectSerializeUtil<T> {
    /**
     * 序列化
     *
     * @param object
     * @return
     */
    public static byte[] serialize(Object object)
    {
        byte[] bytes = null;
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try
        {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            bytes = baos.toByteArray();
        }
        catch (Exception e)
        {
            log.error("serialize", e);
        }
        finally
        {
            IOUtils.closeQuietly(oos);
            IOUtils.closeQuietly(baos);
        }
        return bytes;
    }

    /**
     * 反序列化
     * ByteArrayInputStream是基于内存Byte数组的流，不需要close，当没有强引用的时候会自动被垃圾回收了
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes)
    {
        Object obj = null;
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        try
        {
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        }
        catch (Exception e)
        {
            log.error("unserialize", e);
        }
        finally
        {
            IOUtils.closeQuietly(ois);
            IOUtils.closeQuietly(bais);
        }
        return obj;
    }

}
